﻿using System;
using System.IO;
using System.Collections.Generic;
namespace TicTacToe
{
    
    class MainClass
    {
        static IEnumerable<CPlayer> RoundPlayers(IEnumerable<CPlayer> p){
            while(true){
                foreach(var player in p){
                    yield return player;
                }   
            }
        }

        public static void Main(string[] args)
        {
            var ErrorStream = new StreamWriter(Console.OpenStandardError());
            var game = new CGame(BoardPresenter.Instance());
            var CrossPlayer = new CPlayer(new CCross());
				CrossPlayer.Attach(game);
			var CirclePlayer = new CPlayer(new CCircle());
				CirclePlayer.Attach(game);
			var players = new List<CPlayer> { CirclePlayer, CrossPlayer };
			
            foreach (var player in RoundPlayers(players)){
				Console.Clear();
                if (game.Winner == null)
                    Console.Write(BoardPresenter.Instance().PresentBoard(game));
                else
                {
                    Console.Write($"{game.Winner.Repl};\n Winner winner, chicken dinner!");
                    break;
                }
                foo:try
                    {
                        var place = ConsoleProcessor.GetConsoleInput();
                        player.Play(game, place.Item1, place.Item2);
                    }
                    catch (IndexOutOfRangeException)
                    {
                    ErrorStream.WriteLine("输入数字过少。");
                    ErrorStream.Flush();
                    goto foo;
                    }
                    catch (FormatException)
                    {
                    Console.WriteLine("输入格式错误。");
                    ErrorStream.Flush();
                    goto foo;
                    }

                }
            }
        }
    }

